<template>
  <div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="plus" @click="handleAdd">{{ $t('btn.add') }}</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <vxe-table
      height="600"
      show-overflow
      ref="xTreeRef"
      :column-config="{ resizable: true }"
      :tree-config="{
        parentField: 'parentId',
        reserve: true
      }"
      :row-config="{
        keyField: 'id'
      }"
      :scroll-y="{ enabled: true, gt: 20 }"
      :loading="loading"
      :data="list">
      <template v-for="col in columns">
        <vxe-column
          :field="col.field"
          :title="col.label"
          :tree-node="col['tree-node']"
          :width="col.width"
          :sortable="col.sortable"
          :align="col.align"
          v-if="col.visible">
          <template #default="scope" v-if="col['custom-template']">
            <component :is="col['custom-template'](scope)"></component>
          </template>
        </vxe-column>
      </template>
    </vxe-table>

    <el-dialog :title="title" v-model="open" width="600px" appendToBody draggable>
      <el-form ref="formRef" :model="form" labelWidth="120px">
        <el-row>
          <el-col :lg="24">
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
            <el-form-item :label="$t('m.sort')" prop="orderNum">
              <el-input-number v-model="form.sort" controls-position="right" :min="1" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="handleConfirm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import { vDragable } from 'element-plus-table-dragable'
import { useI18n } from 'vue-i18n'
import { ElMessageBox, FormInstance } from 'element-plus'
import { deepClone, getFormData } from '@/utils'
import modal from '@/plugins/modal'
import { addCategory, deleteCategory, getCategoryWithTree, updateCategory } from '@/api/souvenir/category'
import { getToken } from '@/utils/auth'
const { t } = useI18n()
interface dictOption {
  dictLabel: string
  dictValue: string
}
const statusOptions = ref<dictOption[]>([
  { dictLabel: '在售', dictValue: '1' },
  { dictLabel: '下架', dictValue: '2' }
])
const loading = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
})
interface category {
  id?: number
  name: string
  sort: number
  parentId?: number
}
const list = ref<category[]>()
interface column {
  label?: string
  prop?: string
  type?: string
  width?: string
  align?: string
  'min-width'?: string
  'class-name'?: string
  'show-overflow-tooltip'?: boolean
  'custom-template'?: (scope: any) => {}
  visible: boolean
}
interface columnVxe {
  field?: string
  label?: string
  width?: string
  align?: string
  'custom-template'?: (scope: any) => {}
  visible: boolean
  'tree-node'?: boolean
  sortable?: boolean
}
const columns = ref<columnVxe[]>([
  {
    field: 'name',
    label: '分类名称',
    'tree-node': true,
    visible: true
  },
  {
    field: 'sort',
    label: t('m.sort'),
    visible: true,
    width: '90',
    sortable: true,
    align: 'center'
  },
  {
    field: 'action',
    label: t('btn.operate'),
    visible: true,
    align: 'center',
    width: '160',
    'custom-template': (scope) => {
      return (
        <el-button-group>
          <el-button
            text
            type="primary"
            icon="edit"
            onClick={() => {
              handleUpdate(scope.row)
            }}></el-button>
          {scope.level !== 2 ? (
            <el-button
              text
              type="success"
              icon="plus"
              onClick={() => {
                handleAdd(scope.row)
              }}></el-button>
          ) : (
            ''
          )}

          <el-button
            text
            type="danger"
            icon="delete"
            onClick={() => {
              handleDelete(scope.row)
            }}></el-button>
        </el-button-group>
      )
    }
  }
])
const title = ref('')
const open = ref(false)
const formRef = ref<FormInstance>()
const form = ref<category>({
  name: '',
  sort: 0,
  parentId: undefined
})
const handleUpdate = (row) => {
  title.value = '编辑纪念品分类'
  open.value = true
  formRef.value?.resetFields()
  reset(true, row)
  formRef.value?.clearValidate()
}
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('是否要删除?', '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    try {
      await deleteCategory(row.id)
      modal.msgSuccess('删除成功')
    } catch (error) {
      console.error(error)
      modal.msgError('删除失败')
    }
    getList()
  } catch (error) {}
}
const handleAdd = (row?) => {
  title.value = '新增纪念品分类'
  open.value = true
  formRef.value?.resetFields()
  reset(false)
  formRef.value?.clearValidate()
  if (row != null && row.id != undefined) {
    form.value.parentId = row.id
  } else {
    form.value.parentId = undefined
  }
}
const reset = (isUpdate: boolean, row?: any) => {
  if (isUpdate) {
    form.value = deepClone(row)
  } else {
    form.value = {
      name: '',
      sort: 0,
      parentId: undefined
    }
  }
}
const cancel = () => {
  open.value = false
  reset(false)
}
const handleConfirm = async () => {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (title.value === '新增纪念品分类') {
          const { data } = await addCategory(form.value)
          if (data) {
            modal.msgSuccess('新增成功')
          }
        } else {
          const { data } = await updateCategory(form.value)
          if (data) {
            modal.msgSuccess('编辑成功')
          }
        }
      } catch (error) {
        console.error(error)
        if (title.value === '新增纪念品分类') {
          modal.msgError('新增失败')
        } else {
          modal.msgError('编辑失败')
        }
      }
      open.value = false
      getList()
    }
  })
}

const getList = async () => {
  loading.value = true
  try {
    const { data } = await getCategoryWithTree()
    list.value = data
  } catch (error) {
    console.error(error)
    loading.value = false
  }
  loading.value = false
}
getList()
</script>

<style scoped></style>
